package com.wayhome.srpingbootmybatis.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtils {
    private static final int BUFFER_SIZE = 4096;

    public static void zipFolder(String sourcePath,
                                 OutputStream outputStream) throws IOException {
        try (ZipOutputStream zos = new ZipOutputStream(outputStream)) {
            File sourceDir = new File(sourcePath);
            addFolderToZip("", sourceDir, zos);
        }
    }

    private static void addFolderToZip(String parentPath,
                                       File folder,
                                       ZipOutputStream zos) throws IOException {
        for (File file : folder.listFiles()) {
            if (file.isDirectory()) {
                addFolderToZip(parentPath + file.getName() + "/", file, zos);
                continue;
            }
            try (FileInputStream fis = new FileInputStream(file)) {
                ZipEntry entry = new ZipEntry(parentPath + file.getName());
                zos.putNextEntry(entry);
                byte[] buffer = new byte[BUFFER_SIZE];
                int length;
                while ((length = fis.read(buffer)) > 0) {
                    zos.write(buffer, 0, length);
                }
                zos.closeEntry();
            }
        }
    }
}
